package com.hitqz.robot.biz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.cache.Cache;
import com.hitqz.robot.api.business.entity.JobModeEntity;
import com.hitqz.robot.api.business.enums.WorkStatusEnum;
import com.hitqz.robot.api.common.dto.info.RobotNavInfoDto;
import com.hitqz.robot.biz.mapper.JobModeMapper;
import com.hitqz.robot.biz.service.JobModeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import lombok.RequiredArgsConstructor;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 任务模式
 *
 * @author kehanjiang
 * @date 2025-06-10 09:26:29
 */
@Service
@RequiredArgsConstructor
public class JobModeServiceImpl extends ServiceImpl<JobModeMapper, JobModeEntity> implements JobModeService {

    @Value("${robot.system-type}")
    private String systemType;

    private final Map<String, List<String>> standbyPos = Map.of("lundui", Arrays.asList("CP14", "CP15", "LM7", "LM8"),
            "lunzhou", Arrays.asList("CP192","CP193","LM1", "LM34"));

    @Override
    public boolean updateJobMode(JobModeEntity jobMode) {
        //切换模式需要做前置校验
        //1、当有AGV正在执行任务时，不允许切换单车/双车模式；
        //2、当两车都回“AGV待命点”后才允许切换模式；
        Cache<String, RobotNavInfoDto> robotNavInfoDtoMapCache = SpringUtil.getBean("robotNavInfo");
        for (RobotNavInfoDto robotNavInfo : robotNavInfoDtoMapCache.asMap().values()) {
            if (WorkStatusEnum.WORK.getCode().equals(robotNavInfo.getWorkStatus())) {
                throw new RuntimeException(String.format("%s 正在执行任务，请先完成任务后再切换模式！", robotNavInfo.getRobotSn()));
            }
            if (!standbyPos.get(systemType).contains(robotNavInfo.getCurrentPos().getCode())) {
                throw new RuntimeException(String.format("%s 不在待命点上，请先回待命点后再切换模式！", robotNavInfo.getRobotSn()));
            }
        }

        return this.update(Wrappers.<JobModeEntity>lambdaUpdate()
                .set(JobModeEntity::getMode, jobMode.getMode())
                .set(JobModeEntity::getUpdateTime, LocalDateTime.now()));
    }

    @Override
    public JobModeEntity getDefaultJobMode() {
        return this.getOne(Wrappers.<JobModeEntity>lambdaQuery()
                .last("limit 1"));
    }
}